package com.vvv.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vvv.domain.LoginUser;
import com.vvv.domain.User;
import com.vvv.mapper.MenuMapper;
import com.vvv.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author vvv
 * @date 2023-06-11 15 13
 * discription
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 根据用户名从数据库查询信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            new RuntimeException("用户不存在");
        }
        // 2. 从数据库中查询用户权限信息
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
        // 3. 封装成UserDetails对象，并返回
        return new LoginUser(user, list);
    }
}
